<?php
namespace control;/*
*公积金核算类
*/

class providentFundClass extends adIndexClass
{
    private const title = '公积金核算';
    private const page = 'providentFund';
    private const table = 'provident_fund';

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        if ($workFlow == '公积金记录') {
            $html =
                selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('salary.table.xing_ming')]) .
                selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('salary.table.bu_men')]) .
                text(array("name" => "moon", 'laydate' => ['type' => 'month', 'range' => '~'], "title" => L('salary.table.jkyf')));
        } else {
            $html =
                selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('salary.table.xing_ming')]) .
                selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('salary.table.bu_men')]);
        }

        return $this->search($html, 'menu');
    }

    /**
     * 公积金记录
     *
     */
    public function deduction()
    {
        $json['html'] = $this->homeForm('公积金记录');
        return json_encode($json, 320);
    }

    public function deductionSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
        );
        $and = '';
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('moon')) {
            $timeArr = explode(' ~ ', $this->post('moon'));
            $and .= " and month >='{$timeArr[0]}' and month <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => " month desc,id desc"));
        //获取表头
        $checkAll = $this->checkAll("recordForm", "recordId");
        //获取表头
        $tr[] = array($checkAll, L('salary.table.bu_men'), L('salary.table.zhi_wei'), L('salary.table.yuan_gong'), L('salary.table.jiao_na_yue_fen'), L('salary.table.companyPart')."(" . static::$unit . ")", L('salary.table.personalPart')."(" . static::$unit . ")", L('salary.table.accountDec')."(" . static::$unit . ")", L('salary.table.total')."(" . static::$unit . ")", L('salary.table.bei_zhu'));
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "recordId", "value" => $array['id']),
            );
            $job = query('job', " id = '$array[jobId]'");

            $department = query('department', " id = '$job[departmentId]'");
            //数据库查询
            $staff = query("staff", " stid = '$array[staffId]'");
            //本行
            $tr[] = array($this->dominate($dominate), $department['name'], $job['name'], $staff['name'], $array['month'], $array['companyFund'], $array['personFund'], $array['decMoney'], $array['companyFund'] + $array['personFund'], $array['text']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('salary.table.shan_chu')."</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='recordForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 提交扣款
     * @return bool|string
     */
    public function commitDec()
    {
        $month = date('Y-m', strtotime("-1 month"));
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('salary.table.ti_shi') =>L('salary.table.fund_tip'),
            ),
            array(
                L('salary.table.month').'：' => text(array('name' => 'month', 'laydate' => ['type' => 'month'], 'value' => $month))
            ),
        ), 'formTwo' => 'listForm'));
        //返回
        return $this->layer(array("title" => L('salary.table.gjjkk'), "height" => 226, "width" => 600, "html" => $html));
    }

    /**
     * 账户扣款编辑
     * @return bool|string
     */
    public function commitDecEdit()
    {
        $listId = $this->post('listId');
        $textArr = $this->post('text');
        $decMoneyArr = $this->post('decMoney');
        $month = $this->post('month');//月份
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.fund_edit_permission');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('salary.table.qxzsj');
        } elseif (empty($month)) {
            $json['warn'] = L('salary.table.qxzyf');
        } else {
            $x = 0;
            foreach ($listId as $k => $stid) {
                $record = query(self::table, "month = '$month' and staffId = '$stid'");

                $staff = query('staff', " stid = '$stid'");
                if (empty($record['id'])) {
                    $id = self::getId();
                    $warn = insert(array(
                        "table" => self::table,
                        "field" => [
                            'id' => $id,
                            'staffId' => $stid,
                            'jobId' => $staff['jobId'],
                            'companyFund' => $staff['companyFund'],
                            'personFund' => $staff['personalFund'],
                            'decMoney' => $decMoneyArr[$stid],
                            'text' => $textArr[$stid],
                            'isCommit' => 1,
                            'stid' => $this->control['stid'],
                            'month' => $month,
                            'time' => $this->time
                        ]
                    ));
                } else {
                    $warn = update(array(
                        "table" => self::table,
                        "field" => [
                            'jobId' => $staff['jobId'],
                            'companyFund' => $staff['companyFund'],
                            'personFund' => $staff['personalFund'],
                            'decMoney' => $decMoneyArr[$stid],
                            'text' => $textArr[$stid],
                            'stid' => $this->control['stid'],
                        ],
                        'where' => " id = '$record[id]'"
                    ));
                    $id = $record['id'];
                }
                if ($warn == '新增成功' || $warn == '更新成功') {
                    $x++;
                    //添加日志
                    $text = str_replace(['{{staffName}}','{{name}}','{{month}}','{{id}}'],[$this->control['name'],$staff['name'],$month,$id],L('salary.table.fund_edit'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('salary.table.tax_commit_text'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&menu=record&id=all";
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 查询条件
     *
     * @param string $workFlow
     * @return string
     */
    public function home($workFlow = '公积金扣款'): string
    {
        if ($workFlow == '公积金扣款') {
            $data = [
                "id" => "all",
                "menu" => [
                    "record" => L('salary.table.gjjkk'),
                    "deduction" => L('salary.table.gjjjl'),
                ]
            ];
        }
        $data['html'] = $this->homeForm($workFlow);
        return $this->tab($data);
    }

    /*社保数据-列表页-查询结果*/
    public function homeSearch()
    {
        //当前月份
        $month = date('Y-m');
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
            'workFlow'=>'已复核'
        );
        $and = " and stid not in (select staffId from " . self::table . " where month = '$month') and state in ('试用','转正','留职')";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => " staff", "where" => $where, "order" => " time asc"));

        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('salary.table.bu_men'), L('salary.table.zhi_wei'), L('salary.table.yuan_gong'), L('salary.table.companyPart')."(" . static::$unit . ")", L('salary.table.personalPart')."(" . static::$unit . ")", L('salary.table.zhkk')."(" . static::$unit . ")", L('salary.table.bei_zhu'));
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['stid']),
            );
            $job = query('job', " id = '$array[jobId]'");
            $department = query('department', " id = '$job[departmentId]'");
            //数据库查询
            $staff = query("staff", " stid = '$array[stid]' ");
            $decText = text(array('name' => "decMoney[$array[stid]]", 'class' => 'text textPrice', 'value' => $array['personalFund']));
            $text = text(array('name' => "text[$array[stid]]", 'class' => 'text textPrice', 'value' => ''));
            //本行
            $tr[] = array($this->dominate($dominate), $department['name'], $job['name'], $staff['name'], $array['companyFund'], $array['personalFund'], $decText, $text);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'commitDec', {})\">".L('clock.table.decMoney')."</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr, "orderBySign" => '')) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('salary.table.delProvidentFund');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, recordForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /*批量删除*/
    public function delete()
    {
        $array = $this->post('recordId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.nmzbjgjjjldzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = L('salary.table.sccg');
                $x++;
                $text .= str_replace(['{{name}}', '{{month}}', '{{id}}'], [self::findStaff($info['staffId']), $info['month'], $id], L('salary.table.fund_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.fund_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.fund_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
